package com.learning.server.net;

import com.learning.server.util.ReplyFormat;
import org.apache.axiom.om.OMAbstractFactory;
import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.OMFactory;
import org.apache.axiom.om.OMNamespace;
import org.apache.axis2.AxisFault;
import org.apache.axis2.addressing.EndpointReference;
import org.apache.axis2.client.Options;
import org.apache.axis2.client.ServiceClient;
import org.apache.axis2.rpc.client.RPCServiceClient;
import org.apache.commons.codec.binary.Base64;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.namespace.QName;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.SimpleDateFormat;
import java.util.*;

public class Axis2 {
    public static final String targetEndpoint = "http://ic.xazysoft.cn:8090/IntelliCommunityWebService.asmx";
    public static final String targetNamespace = "http://tempuri.org/";
    public static final String method = "GetAccessRandom";

    String str = new String("good");
    char[] ch = { 'a', 'b', 'c' };

    private static String info_id_list_str = "7091,7091,7091,7091,7091,7091,7200,7228,7278,7402,7407,7407,7407,7407,7407,7407,7407,7407,7407,7407,7407,7407,7623,7915,8170,8201,8209,8210,8212,8213,8214,8215,8217,8219,8221,8222,8223,8225,8226,8227,8228,8229,8230,8231,8233,8235,8237,8238,8239,8240,8241,8242,8246,8247,8248,8250,8251,8252,8253,8254,8257,8258,8259,8261,8262,8264,8265,8267,8268,8269,8275,8278,8279,8705,8705,8705,8705,8705,8705,8705,8705,8705,8705,8705,8705,8705,8705,8705,8705,8705,8705,8705,8705,8705,8705,8799,8799,8799,8799,8799,8799,8799,8799,8799,8824,8842,8849,8849,8865,8865,8872,8872,8872,8872,8872,8872,8872,8872,8872,8904,8904,8904,8904,8904,8904,8904,8904,8904,8920,8920,8920,8920,8920,8920,8920,8920,8920,8936,8936,8936,8936,8936,8936,8936,8936,8936,8944,8944,8944,8944,8944,8944,8944,8944,8944,8960,8960,8960,8960,8960,8960,8960,8960,8960,8961,8961,8961,8961,8961,8961,8961,8961,8961,8968,8968,8968,8968,8968,8968,8968,8968,8968,9113,9113,9113,9113,9113,9113,9113,9113,9113,9196,9196,9196,9196,9196,9196,9208,9208,9394,9394,9394,9394,9394,9394,9394,9394,9394,9394,9394,9394,9394,9394,9394,9394,9394,9394,9394,9394,9394,9874,10031,10031";

    public void change(String str, char ch[]) {
        str = "test ok";
        ch[0] = 'g';
    }


    public static void main(String[] args) throws Exception {

        Axis2 ex = new Axis2();
        ex.change(ex.str, ex.ch);
        System.out.print(ex.str + " and ");
        System.out.print(ex.ch);

//        try{
//            Date date = null;
//            long d = date.getTime();
//
//        }catch (Exception e){
//            //e.printStackTrace();
//            System.out.println(getStackTraceInfo(e));
//        }


//        SimpleDateFormat format = null;
//        String result = null;
//        for(int i = 0; i< 10; ++i) {
//            Thread.sleep(1000);
//            Date targetDate = new Date();
//
//            format = new SimpleDateFormat("yyyyMMddHHmmssS");
//            result = format.format(targetDate);
//
//
//            System.out.println(result);
//        }



//        System.out.println(String.format("%.2f", 0.1));
//
//        System.out.println(Long.parseLong("3CGI",31));
//        System.out.println("integer value of null " + Integer.valueOf(null));
//        String[] info_id_list = info_id_list_str.split(",");
//
//        Set<String> infoSet = new HashSet<>();
//        for(String info_id:info_id_list){
//            infoSet.add(info_id);
//        }
//
//        String s = "";
//        for(String info_id:infoSet){
//           s += info_id+",";
//        }
//
//        System.out.println(s);

//        Map<Integer,Integer> orderCountMap = new HashMap<>();

//        Set<String> hset = new HashSet<>();
//        hset.add("safsafd");
//        hset.add("adsfsa");
//        System.out.println("'===" + hset.toString() + "----=");
//
//        System.out.println((int)48000*8000000/800000);
//
//        BigDecimal a = BigDecimal.valueOf(4800);
//        BigDecimal b = BigDecimal.valueOf(730000);
//        BigDecimal d = BigDecimal.valueOf(670000);


        //BigDecimal m = a.multiply(b).divide(d);
        //System.out.println(m);
        //double result = m.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
        //System.out.println(result);


//        BigInteger a1 = BigInteger.valueOf(48000);
//        BigInteger b1 = BigInteger.valueOf(7300000);
//        BigInteger d1 = BigInteger.valueOf(670000);
//        BigInteger m1 = a1.multiply(b1).divide(d1);
//        System.out.println(m1);
//
//
//        System.out.println(AmountConversion.halfUp2RMB_FEN(m1.intValue(), 10000));


        //int sumCount = orderCountMap.get(1);

        //int a = 0;

//        StringBuilder historyMonthBuilder = new StringBuilder();
//        System.out.println("'===" + historyMonthBuilder.toString() + "----=");
        //System.out.println(50*230*1.0f/89);
//        double i = Double.NaN;
//        double j = 3;
//        int flag = 0;
//        if(i>j || i<= j)
//        {
//            flag = 1;
//        }
//        System.out.println(flag);


//        Map<String,Integer> map = new HashMap<>();
//        System.out.println(map.get("111"));
//        System.out.println("201805".substring(0,4));
//        System.out.println(Integer.valueOf("201805".substring(4)));
        //Weather();
        //testRPCClient();
        //send("asdfas");


        //processCom();
    }

    /**
     * 获取e.printStackTrace() 的具体信息，赋值给String 变量，并返回
     *
     * @param e
     *            Exception
     * @return e.printStackTrace() 中 的信息
     */
    public static String getStackTraceInfo(Exception e) {

        StringWriter sw = null;
        PrintWriter pw = null;

        try {
            sw = new StringWriter();
            pw = new PrintWriter(sw);
            e.printStackTrace(pw);//将出错的栈信息输出到printWriter中
            pw.flush();
            sw.flush();

            return sw.toString();
        } catch (Exception ex) {

            return "发生错误";
        } finally {
            if (sw != null) {
                try {
                    sw.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
            if (pw != null) {
                pw.close();
            }
        }

    }

    public static void Weather() throws Exception {
        ServiceClient serviceClient = new ServiceClient();
        //创建服务地址WebService的URL,注意不是WSDL的URL
        String url = "http://ic.xazysoft.cn:8090/IntelliCommunityWebService.asmx";
        EndpointReference targetEPR = new EndpointReference(url);
        Options options = serviceClient.getOptions();
        options.setTo(targetEPR);
        //确定调用方法（wsdl 命名空间地址 (wsdl文档中的targetNamespace) 和 方法名称 的组合）
        options.setAction("http://tempuri.org/GetAccessRandom");

        OMFactory fac = OMAbstractFactory.getOMFactory();
        /*
         * 指定命名空间，参数：
         * uri--即为wsdl文档的targetNamespace，命名空间
         * perfix--可不填
         */
        OMNamespace omNs = fac.createOMNamespace("http://tempuri.org/", "");
        // 指定方法
//        OMElement method = fac.createOMElement("GetAccessRandom", omNs);
//        method.build();


        OMElement data = fac.createOMElement("GetAccessRandom", omNs);

        // 对应参数的节点
        String[] strs = new String[]{"clientID"};
        // 参数值
        String[] val = new String[]{"92145963"};
        for (int i = 0; i < strs.length; i++) {
            OMElement inner = fac.createOMElement(strs[i], omNs);
            inner.setText(val[i]);
            data.addChild(inner);
        }
        // 发送数据，返回结果
        //OMElement result2 = serviceClient.sendReceive(data);
        //System.out.println(result2.toString());


        // 调用该接口获取登录使用的随机码
        String randomXml = serviceClient.sendReceive(data).toString();
        randomXml = randomXml.replace("&lt;", "<");

        randomXml = randomXml.substring(randomXml.indexOf("<?xml"), randomXml.indexOf("</root>") + "</root>".length());
        System.out.println("randomXml=" + randomXml);


        Document document = DocumentHelper.parseText(randomXml);


        Map randomMap = XmlUtils.Dom2Map(document);

        String random = (String) ((Map) randomMap.get("content"))
                .get("random");

        //process3(process2(random));

        process(random);
    }

    static String process2(String random)throws Exception{
        String key = "mVXJmK8qKMoJ+dCvPR6Tcg==";

        String url = "http://ic.xazysoft.cn:8090/IntelliCommunityWebService.asmx";
        EndpointReference targetEPR = new EndpointReference(url);
        ServiceClient serviceClient2 = new ServiceClient();
        Options options2 = serviceClient2.getOptions();
        options2.setTo(targetEPR);
        //确定调用方法（wsdl 命名空间地址 (wsdl文档中的targetNamespace) 和 方法名称 的组合）
        options2.setAction("http://tempuri.org/SecretReturn");

        OMFactory fac2 = OMAbstractFactory.getOMFactory();

        OMNamespace omNs2 = fac2.createOMNamespace("http://tempuri.org/", "");

        OMElement data2 = fac2.createOMElement("SecretReturn", omNs2);
        // 对应参数的节点
        String[] strs2 = new String[] { "secretKey","strRandom" };
        // 参数值
        String[] val2 = new String[] { key,random };
        for (int i = 0; i < strs2.length; i++) {
            OMElement inner = fac2.createOMElement(strs2[i], omNs2);
            inner.setText(val2[i]);
            data2.addChild(inner);
        }

        String tokenxml = serviceClient2.sendReceive(data2).toString();

        tokenxml = tokenxml.replace("&lt;","<");

        System.out.println("----------------- " + tokenxml);

        tokenxml = tokenxml.substring(tokenxml.indexOf("<SecretReturnResult>")+ "<SecretReturnResult>".length(),tokenxml.indexOf("</SecretReturnResult>"));

        System.out.println("==============secretReturn " + tokenxml);

        return tokenxml;
        //远程调用web服务
//        OMElement result = serviceClient.sendReceive(method);
//        System.out.println(result);

    }


    static void process3(String secretResult)throws Exception{

        String url = "http://ic.xazysoft.cn:8090/IntelliCommunityWebService.asmx";
        EndpointReference targetEPR = new EndpointReference(url);
        ServiceClient serviceClient2 = new ServiceClient();
        Options options2 = serviceClient2.getOptions();
        options2.setTo(targetEPR);
        //确定调用方法（wsdl 命名空间地址 (wsdl文档中的targetNamespace) 和 方法名称 的组合）
        options2.setAction("http://tempuri.org/Login");

        OMFactory fac2 = OMAbstractFactory.getOMFactory();

        OMNamespace omNs2 = fac2.createOMNamespace("http://tempuri.org/", "");

        OMElement data2 = fac2.createOMElement("Login", omNs2);
        // 对应参数的节点
        String[] strs2 = new String[] { "clientID","sercretMsg" };
        // 参数值
        String[] val2 = new String[] { "92145963",secretResult };
        for (int i = 0; i < strs2.length; i++) {
            OMElement inner = fac2.createOMElement(strs2[i], omNs2);
            inner.setText(val2[i]);
            data2.addChild(inner);
        }

        String tokenxml = serviceClient2.sendReceive(data2).toString();

        tokenxml = tokenxml.replace("&lt;","<");

        System.out.println(tokenxml);
        // 登录平台时调用的接口
//        String tokenxml = webserviceManage.Login(clientID, secretMsg);

        //Document document2 = DocumentHelper.parseText(tokenxml);

        //Map tokenMap = XmlUtils.Dom2Map(document2);
        //String token = (String)((Map) tokenMap.get("content")).get("token");

        //System.out.println(token);


        //远程调用web服务
//        OMElement result = serviceClient.sendReceive(method);
//        System.out.println(result);
    }



    static void process(String random)throws Exception{
        String key = "mVXJmK8qKMoJ+dCvPR6Tcg==";
        // 密钥 编码 方式 随机码随机码 编码方式
        byte[] keyt = Base64.decodeBase64(key);

        byte[] newKeyt = new byte[24];
        System.arraycopy(keyt, 0, newKeyt, 0, keyt.length);
        System.arraycopy(keyt, 0, newKeyt, 16, 8);

        SecretKey deskey = new SecretKeySpec(newKeyt, "DESede");
        Cipher c1 = Cipher.getInstance("DESede/ECB/PKCS5Padding");
        c1.init(Cipher.ENCRYPT_MODE, deskey);
        byte[] encrypted = c1.doFinal(random.getBytes("utf-8"));

        String secretMsg = Base64.encodeBase64String(encrypted);// 对获得的随机码进行3des加密

        String url = "http://ic.xazysoft.cn:8090/IntelliCommunityWebService.asmx";
        EndpointReference targetEPR = new EndpointReference(url);
        ServiceClient serviceClient2 = new ServiceClient();
        Options options2 = serviceClient2.getOptions();
        options2.setTo(targetEPR);
        //确定调用方法（wsdl 命名空间地址 (wsdl文档中的targetNamespace) 和 方法名称 的组合）
        options2.setAction("http://tempuri.org/Login");

        OMFactory fac2 = OMAbstractFactory.getOMFactory();

        OMNamespace omNs2 = fac2.createOMNamespace("http://tempuri.org/", "");

        OMElement data2 = fac2.createOMElement("Login", omNs2);
        // 对应参数的节点
        String[] strs2 = new String[] { "clientID","sercretMsg" };
        // 参数值
        String[] val2 = new String[] { "92145963",secretMsg };
        for (int i = 0; i < strs2.length; i++) {
            OMElement inner = fac2.createOMElement(strs2[i], omNs2);
            inner.setText(val2[i]);
            data2.addChild(inner);
        }

        String tokenxml = serviceClient2.sendReceive(data2).toString();

        tokenxml = tokenxml.replace("&lt;","<");

        System.out.println(tokenxml);
        // 登录平台时调用的接口
//        String tokenxml = webserviceManage.Login(clientID, secretMsg);

        //Document document2 = DocumentHelper.parseText(tokenxml);

        //Map tokenMap = XmlUtils.Dom2Map(document2);
        //String token = (String)((Map) tokenMap.get("content")).get("token");

        //System.out.println(token);


        //远程调用web服务
//        OMElement result = serviceClient.sendReceive(method);
//        System.out.println(result);
    }



    static void processCom()throws Exception{

        String url = "http://ic.xazysoft.cn:8090/IntelliCommunityWebService.asmx";
        EndpointReference targetEPR = new EndpointReference(url);
        ServiceClient serviceClient2 = new ServiceClient();
        Options options2 = serviceClient2.getOptions();
        options2.setTo(targetEPR);
        //确定调用方法（wsdl 命名空间地址 (wsdl文档中的targetNamespace) 和 方法名称 的组合）
        options2.setAction("http://tempuri.org/IntelliCommunityService");

        OMFactory fac2 = OMAbstractFactory.getOMFactory();

        OMNamespace omNs2 = fac2.createOMNamespace("http://tempuri.org/", "");

        OMElement data2 = fac2.createOMElement("IntelliCommunityService", omNs2);
        // 对应参数的节点
        String[] strs2 = new String[] { "token","inpuInfo" };
        // 参数值
        String xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
                "<root>\n" +
                "<clientID>92145963</clientID>\n" +
                "<commandType>10012</commandType>\n" +
                "<params>\n" +
                "<communityID>771633E2-C157-4114-939B-53EB9D607FF2</communityID>\n" +
                "</params>\n" +
                "</root>";

        String[] val2 = new String[] { "3039dcd2-89ef-423d-830f-471d0a3a5d02",xml };
        for (int i = 0; i < strs2.length; i++) {
            OMElement inner = fac2.createOMElement(strs2[i], omNs2);
            inner.setText(val2[i]);
            data2.addChild(inner);
        }

        String tokenxml = serviceClient2.sendReceive(data2).toString();

        tokenxml = tokenxml.replace("&lt;","<");

        System.out.println(tokenxml);
        // 登录平台时调用的接口
//        String tokenxml = webserviceManage.Login(clientID, secretMsg);

        //Document document2 = DocumentHelper.parseText(tokenxml);

        //Map tokenMap = XmlUtils.Dom2Map(document2);
        //String token = (String)((Map) tokenMap.get("content")).get("token");

        //System.out.println(token);


        //远程调用web服务
//        OMElement result = serviceClient.sendReceive(method);
//        System.out.println(result);
    }


    public static void testRPCClient(){
        try {
            // 使用RPC方式调用WebService
            RPCServiceClient serviceClient = new RPCServiceClient();
            // 创建WSDL的URL，注意不是服务地址
            String url = "http://ic.xazysoft.cn:8090/IntelliCommunityWebService.asmx";
            // 指定调用WebService的URL
            EndpointReference targetEPR = new EndpointReference(url);
            Options options = serviceClient.getOptions();
            // 确定目标服务地址
            options.setTo(targetEPR);
            // 确定调用方法（wsdl 命名空间地址 (wsdl文档中的targetNamespace) 和 方法名称 的组合）
            options.setAction(targetNamespace + method);
            // 指定方法的参数值
            Object[] parameters = new Object[] {"92145963"};

            // 创建服务名称
            // 1.namespaceURI - 命名空间地址 (wsdl文档中的targetNamespace)
            // 2.localPart - 服务视图名 (wsdl文档中operation的方法名称，例如<wsdl:operation name="getMobileCodeInfo">)
            QName qname = new QName(targetNamespace, method );







            // 调用方法一 传递参数，调用服务，获取服务返回结果集
            OMElement element = serviceClient.invokeBlocking(qname, parameters);
            System.out.println(element);
            /*
             * 值得注意的是，返回结果就是一段由OMElement对象封装的xml字符串。
             * 我们可以对之灵活应用,下面我取第一个元素值，并打印之。因为调用的方法返回一个结果
             */
            String result = element.getFirstElement().getText();
            System.out.println(result);


            // 调用方法二 getPrice方法并输出该方法的返回值
            // 指定方法返回值的数据类型的Class对象
            Class[] returnTypes = new Class[] {String.class};
            Object[] response = serviceClient.invokeBlocking(qname, parameters, returnTypes);
            String r = (String) response[0];
            System.out.println(r);

        } catch (AxisFault e) {
            e.printStackTrace();
        }
    }



    public static String send(String paramData) {

        try {
            RPCServiceClient client = new RPCServiceClient();
            Options options = client.getOptions();
            options.setTo(new EndpointReference(targetEndpoint));
            options.setTimeOutInMilliSeconds(1000 * 60 * 5);// 毫秒单位
            options.setAction(method);
            Object[] response = client.invokeBlocking(new QName(targetNamespace, method), new Object[]{paramData}, new Class[]{String.class});
            String results = (String) response[0];
            //logger.info("WebService请求返回结果: \r\n{}", Xmls.format(results));
            return results;
        } catch (Exception e) {
            //logger.error("WebService请求异常, Cause:{}, Message:{}", e.getCause(), e.getMessage());
            e.printStackTrace();
            return null;
        }
    }




}
